#!/usr/bin/env node
'use strict';

var Workshopper    = require('workshopper')
  , path           = require('path')
  , menu           = require('./exercises/menu')
  , hooray         = require('workshopper-hooray')
  , more           = require('workshopper-more')
  , log            = require('workshopper/print-text')
  , spawn          = require('child_process').spawn
  , srcdir         = path.join(__dirname, 'src')
  , appname        = 'learnuv'
  , learnuv_config = path.join(process.env.HOME || process.env.USERPROFILE, '.config', appname)
  , currentJSON    = path.join(learnuv_config, 'current.json')

function getCurrentTarget() {
  var currentKey
  try {
    currentKey = require(currentJSON);
    return currentKey.toLowerCase().replace(/ /g, '_');
  } catch(e) {
    console.error('Please run ./learnuv first and select an exercise');
    process.exit();
  }
}

function buildCurrentTarget(tool) {
  process.env.CURRENT_TARGET = getCurrentTarget();
  spawn('npm', [ 'run', tool ], { stdio: 'inherit', env: process.env })
}

if (process.argv[2] && process.argv[2].toLowerCase() === 'ninja')
  return buildCurrentTarget('ninja');

if (process.argv[2] && process.argv[2].toLowerCase() === 'make')
  return buildCurrentTarget('make');

if (process.argv[2] && process.argv[2].toLowerCase() === 'xcode')
  return spawn('npm', [ 'run', 'xcode' ], { stdio: 'inherit' });

function fpath (f) {
  return path.join(__dirname, f)
}

Workshopper.prototype._printUsage = function printUsage() {
  log.file(this.appName, this.appDir, path.join(__dirname, './workshopper/usage.txt'))
}

var ws = new Workshopper({
    name        : appname
  , title       : 'LEARNUV FOR FUN AND PROFIT!'
  , subtitle    : '\x1b[23mSelect an exercise and hit \x1b[3mEnter\x1b[23m to begin'
  , exerciseDir : fpath('./exercises/')
  , appDir      : __dirname
  , footerFile  : path.join(__dirname, 'workshopper', 'footer.md')
  , helpFile    : path.join(__dirname, 'workshopper', 'help.txt')
  , menu        : { fg: 'green', bg: 0 }
  , commands    : [
      { name    : 'more'
      , menu    : false
      , short   : 'm'
      , handler : more
      }
    ]
  , onComplete: hooray
})

/* vim ft:javascript */
